<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HEIC Converter to PNG</title>
</head>
<body>
  <h1>HEIC图片格式转换</h1>

  <form id="form">
    <label for="files">选择文件(可多选，CTRL + A 可全选):</label>
    <input type="file" id="files" name="files" multiple accept=".heic,image/heic,image/heif"><br><br>
    <span>转换目标类型：</span>
    <select id="ctype">
      <option value="image/png">png</option>
      <option value="image/jpeg">jpeg/jpg</option>
      <option value="image/gif">gif</option>
    </select>
    <br><br>
    <input type="submit" value="转换并下载">

    <button type="button" id="clear">清除选择的文件</button>
  </form>

  <p>
    P.S.
    The conversion is done in the browser.
    <br>Thus, no data is transferred to the server.
    <br>Thanks to <a href="https://github.com/alexcorvi/heic2any" target="_blank">alexcorvi/heic2any</a>.
  </p>
  <script src="./jszip.min.js"></script>
  <script src="./heic2any.min.js"></script>
  <script src="./multi-download.js"></script>
  <script src="./FileSaver.js"></script>
  <script>
    const form = document.querySelector('#form');

    form.addEventListener('submit', function(e) {
      e.preventDefault();
      const ctpye = document.getElementById('ctype').value
      const files = document.querySelector('#files').files;

      if (files.length === 0) {
        alert('Please select files');
        return;
      }

      const urls = [];
      const zip = new JSZip();
      const filesArray = Array.from(files);
      let zipfilecount = 0;
      filesArray.forEach(async file => {
        try {
          const blob = new Blob([file]);
          const convertedBlob = await heic2any({ blob ,  toType: ctpye,});
          if(filesArray.length == 1){
            const objectURL = URL.createObjectURL(convertedBlob);
            urls.push({
              name: file.name.slice(0, -5)+ '.' + ctpye.slice(6),
              url: objectURL
            });
            multiDownload(urls);
            return
          }
          zip.file(file.name.slice(0, -5)+ '.' +ctpye.slice(6), convertedBlob, {base64:true});
          zipfilecount += 1;
          
          if(zipfilecount === filesArray.length) {
            //multiDownload(urls);
            zip.generateAsync({type:"blob"})
            .then(function(content) {
                // see FileSaver.js
                saveAs(content, "result.zip");
            });
          }
        } catch(err) {
          alert(err.message || 'Something went wrong');
          console.log(err);
        }
      });
    });

    const clear = document.querySelector('#clear');
    clear.addEventListener('click', function() {
      document.querySelector('#form').reset();
    });
  </script>
</body>
</html>
